import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getOil, getIdOil, createOil, updateOil, delteOil } from './oil.service';

/**
 *  获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let pageNo = request.query.pageNo

  const data = await getOil(10, parseInt(`${pageNo}`, 10));
  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const oilDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdOil(parseInt(postId, 10));

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let oliModel = request.body;

  // 创建内容
  if (oliModel.id && oliModel.id > 0) {
    const data = await updateOil(oliModel, parseInt(oliModel.id, 10));
    response.send(data);
  } else {
    const data = await createOil(oliModel);
    response.send(data);
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 获取内容
  const post = _.pick(request.body, ['ninety_five', 'ninety_two', 'ninetyTwo', 'zero', 'date']);

  // 更新内容
  try {
    const data = await updateOil(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.params;

  // 删除内容
  try {
    const data = await delteOil(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}
